#include "dxsurface.h"
#include "logger.h"

using namespace std;

DXSurface::DXSurface()
{ }

DXSurface::DXSurface(GameGraphic* pGraphic, const char* nameImg)
{	
    pd3ddv = (IDirect3DDevice9*)pGraphic->GetDevice();
    if FAILED(D3DXGetImageInfoFromFile(nameImg, &infoImg))
    {
        (Logger::GetLogger("DXSurface")).Error("Can't get image info!");
    }
    if FAILED(pd3ddv->CreateOffscreenPlainSurface(infoImg.Width,
                                            infoImg.Height,
                                            D3DFMT_X8R8G8B8,
                                            D3DPOOL_DEFAULT,
                                            &pSurface,
                                            NULL))
    {	
        (Logger::GetLogger("DXSurface")).Error("Can't create offscreen surface!");
    }
    if FAILED(D3DXLoadSurfaceFromFile(pSurface,
                                        NULL,
                                        NULL,
                                        nameImg,
                                        NULL,
                                        D3DX_DEFAULT,
                                        0,
                                        NULL))
    {	
        (Logger::GetLogger("DXSurface")).Error("Can't load surface from image!");
    }
}

float DXSurface::GetWidth()
{	
    return (float)infoImg.Width;
}

float DXSurface::GetHeight()
{	
    return (float)infoImg.Height;
}

void DXSurface::Draw()
{	
    if (pd3ddv != NULL)
    {	
        IDirect3DSurface9* pBackBuffer = NULL;
        pd3ddv->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);
        pd3ddv->StretchRect(pSurface, NULL, pBackBuffer, NULL, D3DTEXF_NONE);
        pBackBuffer->Release();
    }
    return;
}

void DXSurface::Draw(int posX, int posY, int scale)
{	
    if (pd3ddv != NULL)
    {	
        IDirect3DSurface9* pBackBuffer = NULL;
        pd3ddv->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, &pBackBuffer);
        RECT destRect = { posX, posY, posX + infoImg.Width * scale, posY + infoImg.Height * scale};
        pd3ddv->StretchRect(pSurface, NULL, pBackBuffer, &destRect, D3DTEXF_NONE);
        pBackBuffer->Release();
    }
    return;
}

DXSurface::~DXSurface()
{	
    if (pSurface != NULL)
        pSurface->Release();
}